<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <div>
        <button id="start">start</button>
        <button id="stop">stop</button>
    </div>
    <script src="jq.js"></script>
    <script src="shape.js"></script>
    <script>
        var canvas = document.getElementById('canvas'),
            context = canvas.getContext('2d'),
            play = true,
            start = document.getElementById('start'),
            stop = document.getElementById('stop')
        //创建用于控制动画的按钮
        $(start).hide().click(function () {
            $(this).hide()
            $(stop).show()
            play = true
            animate()
        })
        $(stop).click(function () {
            $(this).hide()
            $(start).show()
            play = false
        })

        //运动的正方形
        var shape1 = new Shape(0, 10)
        var shape2 = new Shape(10, 30)
        var shape3 = new Shape(20, 50)
        var direction = 5
        var shapes = []
        shapes.push(shape1)
        shapes.push(shape2)
        shapes.push(shape3)
        console.log(shapes)


        function animate() {
            context.clearRect(0, 0, canvas.width, canvas.height)
            for (var i = 0; i < shapes.length; i++) {
                if (shapes[i].x >= canvas.width) {
                    direction = -5
                } else if (shapes[i].x <= 0) {
                    direction = 5
                }
                shapes[i].x += direction
                context.fillRect(shapes[i].x, shapes[i].y, 10, 10)
            }

            if (play) {
                setTimeout(animate, 1000 / 60)
            }
        }
        animate()
    </script>
</body>

</html>